/**
 * 价格提报审批页
 */
import React, { Component } from 'react';
import { Alert, StyleSheet, Image, PixelRatio, ScrollView, Text, View, Dimensions, TouchableOpacity, DeviceEventEmitter } from "react-native";
import { style } from '../../../theme/style';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api.js';
import { PriceEchartsPage } from '../component/PriceEchartsPage';
import { MyListPage } from '../component/MyListPage'
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { Common } from '../../../component/common/Common.js';
import { ApprovalView, RefuseModal } from '../../../component/ModalVerifylComponent.js';
import ToastUtil from '../../../utils/toast'

const ScreenWidth = Dimensions.get('window').width;
const scale = ScreenWidth / 375;

let lsData = [];
let responseData = [];
let goodsCateId = '';
let nextOnoff = true;
let nextText = '记录';
const sendApprovalDate = {};
let aprovalVisible = false;
// const panelViewBorder = Platform.OS == 'android' ? { borderColor: '#F1F1F1', borderWidth: 1 / PixelRatio.get(), } : null;

//审批列表 -> 待审批
export class PriceAuditApprovalPage extends Component {

	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '审批详情',
			headerTintColor: style.color.white,//
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color="#fff" />,
			headerRight: (
				<Text style={{ opacity: 0 }}></Text>
			),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: style.head.headerTitleStyle
		}
	};

	requesting;
	constructor(props) {
		super(props);
		this.state = {
			pageStatus: {
				status: 'loading', //empty
				status1: 'loading'
			},
			onoff: false, // 打开tab 
			numWidth: 8,
			colorOnoff: true, // 输入框的颜色变化
			slideOnoff: true,
			loginBtnDisabled: true,
			data: [],
			modalVisible: false,   //提交申请成功-弹框
			showProduct: false,  //选择商品弹框
			lsArr: [],
			selectIndex: 0,  // 选择商品
			selectName: '',  //商品名称
			selectShow: false,  //选择商品 箭头显示隐藏
			price: '0.00', //建议价
			refuseModalVisible: false,
			resultModalVisible: false,
			nodeData: [],
			echartsData: [],
		}

		this.getApprovalView = this.getApprovalView.bind(this);
		this._fetchApproval = this._fetchApproval.bind(this);
		this.applyId = this.props.navigation.state.params.paramsData.applyId;
		this.status = this.props.navigation.state.params.paramsData.status;
		this.originPrice = this.props.navigation.state.params.paramsData.suggestedPrice;//suggestedPrice/originPrice
		//20181023新增
		this.goodsId = this.props.navigation.state.params.paramsData.goodsId;
		this.goodsCateId = this.props.navigation.state.params.paramsData.goodsCateId;
		//20181024
		this.formKey = this.props.navigation.state.params.paramsData.formKey;
		this.taskId = this.props.navigation.state.params.paramsData.taskId;
		this.businessKey = this.props.navigation.state.params.paramsData.businessKey;
		this.goodsName = this.props.navigation.state.params.paramsData.goodsName;
		this.branchId = this.props.navigation.state.params.paramsData.branchId;
		//sendApprovalDate.businessKey = this.props.navigation.state.params.applyId;
		sendApprovalDate.formKey = this.props.navigation.state.params.paramsData.formKey;
		sendApprovalDate.taskId = this.props.navigation.state.params.paramsData.taskId;
		sendApprovalDate.businessKey = this.props.navigation.state.params.paramsData.applyId;
		aprovalVisible = (this.status != 'PASS' && this.status != 'UNPASS') ? true : false;
		console.log(this.status, aprovalVisible);
	}

	_setWidth = (val) => {
		let wLen = val.length + 1; s
		this.setState({
			numWidth: wLen > 5 ? wLen : 5
		})
	}

	_slideOnoff = () => {
		this.setState({
			slideOnoff: !this.state.slideOnoff
		})
	}

	_showProductHanld = () => {
		if (lsData.length > 1) {
			this.setState({
				showProduct: !this.state.showProduct
			})
		}
	}

	_closeBomb = (index) => {
		this.setState({
			showProduct: false,
			selectIndex: index,
			data: responseData[index],
			selectName: lsData[index],
			price: responseData[index].suggestedPrice
		});
		goodsCateId = responseData[index].goodsCateId;
	}

	async componentWillMount () {
		this._getPriceDetail();
		//this._approvalNode();
		this._getTrend();
		this.props.navigation.setParams({
			navigatePress: this._navigatePress
		});
	}
	// 暂时不用

	//查询审批节点
	async _approvalNode (processInstanceId) {
		let responseData1 = await HTTP.GET(API_GENERATE(API.APPROVAL_NODE) + '?bizId=' + this.applyId + '&bizObjType=14&processInstanceId=' + processInstanceId);
		this.setState({
			nodeData: responseData1
		});
	};


	_navigatePress = () => {
		if (nextOnoff) {
			this.props.navigation.navigate('SiterRecordPage', { goodsCateId });
		} else {
			// alert('无记录')
		}

	}

	async _getPriceDetail () {
		//alert(this.goodsCateId + "**" + this.goodsId);
		let sendData = {
			onrefresh: false,
			pageNo: 1,
			applyId: this.applyId
		}

		let responseData = await HTTP.POST(API_GENERATE(API.PRICE_DETAIL), sendData);
		if (responseData) {
			this._approvalNode(responseData.processInstanceId);
			lsData = [responseData.goodsCateName];

			this.setState({
				pageStatus: {
					status: 'data'
				},
				data: responseData,
				onoff: true,
				lsArr: lsData,
				selectName: lsData[0],
				selectShow: lsData.length > 1 ? true : false,
				price: responseData.suggestedPrice && responseData.suggestedPrice.toString(),
				lastPrice: responseData.lastPrice
			});
			goodsCateId = responseData.goodsCateId;
		} else {
			this.setState({
				pageStatus: {
					status: 'error',
					onErrorPress: () => {
						this._getPriceDetail();
						this.setState({
							pageStatus: {
								status: 'loading'
							},
						});
					}
				},
			});
		}
	}
	async _fetchApproval1 () {
		this.setState({
			refuseModalVisible: false,
		});
		if (this.requesting) return;
		const { approvalType } = sendApprovalDate;
		this.requesting = true;
		const responseData = await HTTP.POST(API_GENERATE(API.APPRO_PRICE), sendApprovalDate);
		const msg = (approvalType == 'PASS') ? '审批成功' : '驳回成功';
		if (responseData) {
			ToastUtil.showSuccess(msg).then(() => { this._goBack(); })
		} else {
			this.requesting = false;
		}
	}
	// 返回上一个页面
	_goBack = () => {
		DeviceEventEmitter.emit('priceApprovalListener');
		setTimeout(() => {
			this.requesting = false;
		}, 1000);
		this.props.navigation.goBack();
	}

	async _getTrend () {
		let sendData1 = {
			//nrefresh: false,
			goodsId: this.goodsId,
			branchId: this.branchId,
		}
		let xData = [];
		let yData = [];
		let responseData1 = await HTTP.POST(API_GENERATE(API.PRICE_TREND), sendData1);
		if (responseData1) {
			responseData1.map((item, index) => {
				xData[index] = item.prodDate.split(' ')[0];
				yData[index] = item.suggestedPrice;
			})
		}
		let echartsData = [{ prodDate: xData, marketPrice: yData }];
		this.setState({
			echartsData: echartsData
		})
		//console.log('趋势responseData1', responseData1);
	}
	async _fetchApproval () {
		if (this.requesting) return;
		sendApprovalDate['remark'] = sendApprovalDate['auditRemark'] == 'undefined' ? '' : sendApprovalDate['auditRemark'];
		sendApprovalDate['auditResult'] = sendApprovalDate['approvalType'] == 'PASS' ? 1 : 0;
		const { approvalType } = sendApprovalDate;
		/*if (approvalType == 'PASS') {
			Alert.alert('审批确认', '您好，确认审批该单吗？', [
				{ text: '取消', onPress: () => { console.log('取消') } },
				{ text: '好', onPress: () => { this._sendCodeOk() } },
			]);
		}*/
		if (approvalType == 'PASS') {
			Alert.alert('审批确认', `确认审批该现货价提报单吗?`, [
				{ text: '取消', onPress: () => { console.log('取消') } },
				{
					text: '确认', onPress: () => {
						this._fetchApproval1()
					}
				},
			]);
		} else {
			this.setState({
				refuseModalVisible: false,
			});
			let remark = (sendApprovalDate['remark'] + "").trim();
			if (!sendApprovalDate['remark'] || remark.length == 0) {
				ToastUtil.showError('请输入驳回原因');
				return;
			}
			this.requesting = true;
			const responseData = await HTTP.POST(API_GENERATE(API.APPRO_PRICE), sendApprovalDate);
			const msg = (approvalType == 'PASS') ? '审批成功' : '驳回成功';
			if (responseData) {
				ToastUtil.showSuccess(msg).then(() => { this._goBack(); })
			} else {
				this.requesting = false;
			}
		}
		/**/
	}

	getApprovalView () {
		const { data } = this.state;
		const finalPrice = '' + data.finalPrice || '';
		sendApprovalDate.finalPrice = finalPrice;
		return aprovalVisible ? (
			<View style={{ backgroundColor: '#fff', }}>
				{/*<View style={styles.quantityView}>
					<Text style={styles.text}>经营计划部建议价</Text>
					<TextInput
						ref="quantityInput"
						style={[styles.textInput, styles.quantityInput]}
						underlineColorAndroid='transparent'
						placeholder={"请输入"}
						placeholderTextColor="#999"
						maxLength={30}
						editable={true}
						defaultValue={finalPrice}
						keyboardType="numeric"
						onChangeText={(txt) => { sendApprovalDate.finalPrice = txt }}
					/>
		</View>*/}
				<ApprovalView agreePress={async () => {
					sendApprovalDate.approvalType = 'PASS';
					this._fetchApproval();
				}} refusePress={() => {
					this.setState({
						refuseModalVisible: true
					})
				}} />
			</View>
		) : null;
	}

	_getApprovalView1 () {
		const { data, nodeData } = this.state;
		//var returnStr = "<View style={[styles.spotView, styles.unCheckView]}></View>< View style = { [styles.lineView, styles.unCheckView]} ></View><View style={[styles.spotView, styles.checkView]}></View><View style={[styles.lineView, styles.checkView]}></View><View style={[styles.spotView, styles.checkView]}></View>";
		if (nodeData != null && nodeData.length > 0) {
			return (
				<TouchableOpacity style={{ flexDirection: 'row' }}>
					{
						//nodeData.forEach((item, i) => {
						(
							<TouchableOpacity >
								<View style={[styles.spotView, styles.unCheckView]}></View>
								<View style={[styles.lineView, styles.unCheckView]} ></View>
								<View style={[styles.spotView, styles.checkView]}></View>
								<View style={[styles.lineView, styles.checkView]}></View>
								<View style={[styles.spotView, styles.checkView]}></View>
							</TouchableOpacity>
						)
						//})
					}

				</TouchableOpacity>
			);
		}
	}

	render () {
		let { echartsData, pageStatus, onoff, numWidth, price, colorOnoff, selectIndex, slideOnoff, loginBtnDisabled, refuseModalVisible, newLotData, nodeData, lastPrice } = this.state;
		let { goodsCateName, goodsCateId, marketPrice, yesterdayPrice, adjustRange, referencePrice, applyDetailVOS,
			oderPriceList, midMarketPrice, uom, suggestedPrice, yesdayPrice, statusName } = this.state.data;
		let downImg = require('../../../imgs/my-siter/down.png');
		let upImg = require('../../../imgs/my-siter/up.png');
		let rightImg = require('../../../imgs/global/success.png');
		let emptyImg = require('../../../imgs/global/option.png');
		let correctImg = require('../../../imgs/store/success.png');//\imgs\global
		let errorImg = require('../../../imgs/store/fail.png');//\imgs\global
		adjustRange = suggestedPrice - (lastPrice == null ? 0 : lastPrice);
		const approvalView = this.getApprovalView();
		const approvalView1 = this._getApprovalView1();
		return (
			<View style={styles.container}>
				{
					pageStatus.status === 'data' ? (
						<View style={{ flex: 1 }}>
							<View style={{ flexDirection: 'row', backgroundColor: '#0087FF' }}>
								<View style={{ marginLeft: 40 * scale, }}>
									<Text style={{ color: '#fff', fontSize: 12 * scale, }} >商品名称</Text>
									<Text style={{ color: '#fff', fontSize: 16 * scale, width: 220 * scale, marginTop: 14 * scale, marginBottom: 19 * scale, }} numberOfLines={1} ellipsizeMode='tail'>{this.goodsName}</Text>
								</View>
								<View style={{ marginLeft: 10 * scale, }}>
									<Text style={{ color: '#fff', fontSize: 12 * scale, }}>今日提报价</Text>
									<Text style={{ color: '#fff', fontSize: 16 * scale, marginTop: 14 * scale, marginBottom: 19 * scale, }}>{this.simpleFormatAsMoney(suggestedPrice)}{uom || '元'}</Text>
								</View>
							</View>

							<ScrollView>
								<View style={styles.listBox}>
									{/*<View style={[styles.list, styles.line]}>
										<Text style={styles.listText}>市场价</Text>
										<Text style={styles.listText}>{midMarketPrice || '无'}</Text>
								</View>*/}
									<View style={[styles.list, styles.line]}>
										<Text style={styles.listText}>上次现货价</Text>
										<TouchableOpacity style={styles.slideBox} onPress={() => { this._slideOnoff() }}>
											<Text style={styles.listText}>{lastPrice || '无'}</Text>
											{oderPriceList && oderPriceList.length > 0 ? <Image style={[styles.imgSlide, !slideOnoff ? styles.rotateX180 : null]} source={require('../../../imgs/Group.png')} /> : null}
										</TouchableOpacity>
									</View>
									<View style={slideOnoff ? styles.slideHidden : null}>
										{oderPriceList && oderPriceList.length > 0 ? <MyListPage listData={oderPriceList} /> : null}
									</View>

									<View style={styles.list}>
										<Text style={styles.listText}>调整幅度</Text>
										<View style={{ flexDirection: 'row', alignItems: 'center' }}>
											<Text style={styles.listText}>{Math.abs(adjustRange)}</Text>
											<Image source={adjustRange >= 0 ? upImg : downImg} style={{ marginLeft: 5 * scale }} />
										</View>
									</View>
								</View>
								{onoff ? <PriceEchartsPage data={echartsData || []} /> : null}
								<View style={{ width: 375 * scale, backgroundColor: '#fff', marginTop: 12 * scale, }}>
									<Text style={{ fontSize: 12 * scale, color: '#555555', marginLeft: 22 * scale, marginTop: 13 * scale, }}>进行流程</Text>
									<View style={{ marginTop: 16 * scale, marginBottom: 20 * scale, flexDirection: 'row' }}>
										<View style={{ flexDirection: 'row' }}>

											{
												nodeData && nodeData.length > 0 ? (<View>
													{
														nodeData.map((item, i) => {
															let lsArr = item.auditTime ? item.auditTime.split(' ') : [' ', ' '];
															return (<View key={'top' + i}>
																<Text style={styles.topText}>{lsArr[0]}</Text>
																<Text style={styles.bottomText}>{lsArr[1]}</Text>
															</View>)
														})
													}
												</View>) : null
											}

										</View>
										<View style={{ marginLeft: 19 * scale, flexDirection: 'row', marginTop: 24 * scale, }}>
											{
												nodeData && nodeData.length > 0 ? (<View>
													{
														nodeData.map((item, i) => {
															return (nodeData && nodeData.length > 1 && i != nodeData.length - 1 ? <View key={'line' + i}><View style={[styles.spotView, { backgroundColor: item.logId ? '#2F7BFF' : '#EAEAEA' }]}></View>
																<View style={[styles.lineView, { backgroundColor: item.logId ? '#2F7BFF' : '#EAEAEA' }]}></View></View> : <View key={'line' + i} style={[styles.spotView, styles.checkView]}></View>)
														})
													}
												</View>) : null
											}
										</View>
										<View style={{ flexDirection: 'row', marginLeft: 20 * scale, marginTop: 18 * scale, }}>
											{
												nodeData && nodeData.length > 0 ? (<View>
													{
														nodeData.map((item, i) => {
															let showImg = item.auditResultName === '驳回' ? errorImg : correctImg;
															let auditStyle = nodeData.length - 1 != i ? (item.auditResultName === '驳回' ? { marginBottom: 12 * scale } : { marginBottom: 27 * scale }) : null;
															return (<View key={'down' + i}>
																<View style={{ flexDirection: 'row' }}><Text style={[styles.userText, item.auditResultName === '驳回' ? null : auditStyle]}>{nodeData.length - 1 != i ? null : item.auditStaffName}{nodeData.length - 1 != i ? (item.taskName + (item.auditStaffName ? (':' + item.auditStaffName) : '')) : null}</Text>{nodeData.length - 1 != i && item.logId ? <Image source={showImg} style={styles.correct}></Image> : null}</View>
																{item.auditResultName === '驳回' ? <Text style={[styles.userText, auditStyle]}>{item.remark}</Text> : null}
															</View>)
														})
													}
												</View>) : null
											}

										</View>
									</View>
								</View>
							</ScrollView>
						</View>
					) : (<PageStatusIndex {...pageStatus} />)
				}
				{statusName == '审批驳回' ? null : approvalView}
				<RefuseModal visible={refuseModalVisible} btnPress={(auditRemark) => {
					console.log(auditRemark);
					sendApprovalDate.approvalType = 'UNPASS';
					sendApprovalDate.auditRemark = auditRemark;
					this._fetchApproval();
				}} bgPress={() => {
					this.setState({
						refuseModalVisible: false,
					});
				}} />
			</View>
		)
	}

	simpleFormatAsMoney (mnt) {
		mnt -= 0;
		mnt = (Math.round(mnt * 100)) / 100;
		return (mnt == Math.floor(mnt)) ? mnt + '.00' : ((mnt * 10 == Math.floor(mnt * 10)) ? mnt + '0' : mnt);
	}
}

const styles = StyleSheet.create({
	priceTopCellText: {
		fontSize: 22 * scale,
		color: '#404040'
	},
	priceTopCell: {
		justifyContent: 'center',
		alignItems: 'center',
	},
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray //'#fff'
	},
	TitleBox: {
		width: '100%',
		height: 92 * scale,
		backgroundColor: style.color.themeColor
	},
	title: {
		lineHeight: 42 * scale,
		color: style.color.white,
		fontSize: 18 * scale,
		paddingLeft: 23 * scale
	},
	listBox: {
		backgroundColor: style.color.white
	},
	list: {
		flexDirection: 'row',
		paddingTop: 15 * scale,
		paddingBottom: 15 * scale,
		marginLeft: 15 * scale,
		marginRight: 15 * scale,
		alignItems: 'center',
		justifyContent: 'space-between'
	},
	listText: {
		fontSize: 13 * scale,
		color: style.color.dark
	},
	bomb: {
		width: 375 * scale,
		height: 100 * scale,
		paddingLeft: 18 * scale,
		position: 'absolute',
		top: 42 * scale,
		zIndex: 9,
		alignItems: 'center',
		flexDirection: 'row',
		justifyContent: 'center',
	},
	bombShadow: {
		width: 345 * scale,
		height: 97 * scale,
		position: 'absolute',
		top: 0 * scale,
		left: 15 * scale,
	},
	bombText: {
		fontSize: 13 * scale,
		color: style.color.darkGray,
		paddingLeft: 20 * scale,
		paddingTop: 16 * scale
	},
	imgSlide: {
		width: 11 * scale,
		height: 6 * scale,
		tintColor: style.color.darkGray,
		marginLeft: 5 * scale
	},
	slideBox: {
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center'
	},
	slideHidden: {
		height: 0,
		width: 0,
		overflow: 'hidden'
	},
	rotateX180: {
		transform: [{ rotateX: '180deg' }]
	},
	line: {
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.border
	},
	selectStyle: {
		width: 13 * scale,
		height: 7 * scale,
		marginLeft: 5 * scale
	},
	text: {
		fontSize: 12 * scale,
		color: '#404040'
	},
	textInput: {
		borderWidth: 0,
		fontSize: 13 * scale,
		color: '#404040',
		width: '100%',
		height: 42 * scale,
		padding: 0,
		alignSelf: 'center',
	},
	quantityInput: {
		marginLeft: 30 * scale,
		alignSelf: 'center'
	},
	quantityView: {
		flexDirection: 'row',
		height: 50 * scale,
		alignItems: 'center',
		paddingLeft: 14 * scale,
		borderTopColor: '#e4e4e4',
		borderTopWidth: 1 / PixelRatio.get(),
	}, topText: {
		marginTop: 12 * scale,
		fontSize: 12 * scale,
		marginLeft: 62 * scale,
	}, bottomText: {
		fontSize: 10 * scale,
		marginLeft: 62 * scale,
	}, userText: {
		fontSize: 12 * scale,
		color: '#404040'
	}, userMargin: {
		marginTop: 27 * scale,
	}, lineView: {
		marginLeft: 1 * scale,
		width: 3 * scale,
		height: 38 * scale, //backgroundColor: '#404040'
	}, spotView: {
		width: 5 * scale,
		height: 5 * scale,
		//backgroundColor: '#404040',
		borderRadius: 5 * scale,
	}, checkView: {
		backgroundColor: '#2F7BFF'
	}, unCheckView: {
		backgroundColor: '#404040'
	}, correct: {
		width: 13 * scale,
		height: 10 * scale,
		marginLeft: 7 * scale,
		marginTop: 4 * scale,
		marginBottom: 10 * scale,
	}

})